package org.example.cloudapply.repository;

import org.apache.ibatis.annotations.*;
import org.example.cloudapply.entity.Application;
import org.example.cloudapply.vo.ApplicationDetailVO;

import java.awt.print.Pageable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Mapper
public interface ApplicationRepository {


    @Select("SELECT a.* FROM applications a " +
            "JOIN users u ON a.user_id = u.user_id " +
            "WHERE u.openid = #{openid} " +
            "ORDER BY a.apply_time DESC")
    List<Application> findByOpenid(String openid);

    //处理申请
    @Select("SELECT " +
            "a.apply_id, a.cloud_type, a.status, a.apply_time, a.handle_time, " +
            "a.account_info, a.reject_reason, a.name, a.role, a.school_id, " +
            "a.email, a.phone, t.cpu_cores, t.memory_gb, a.gpu_enabled, a.duration_days " +
            "FROM applications a " +
            "JOIN instance_templates t ON a.template_id = t.template_id " +
            "WHERE a.status = 'pending' " +
            "ORDER BY a.apply_time DESC")
    List<Map<String, Object>> findPendingApplications();
    //更新操作时间
    @Update("UPDATE applications SET " +
            "status = #{status}, " +
            "handle_time = NOW(), " +
            "account_info = #{accountInfo}, " +
            "reject_reason = #{rejectReason} " +
            "WHERE apply_id = #{applyId}")
    int updateApplicationStatus(Application application);
    //查找
    @Select("SELECT SUM(t.cpu_cores) AS totalCpu, " +
            "SUM(t.memory_gb) AS totalMemory, " +
            "SUM(CASE WHEN a.gpu_enabled THEN 1 ELSE 0 END) AS totalGpu " +
            "FROM applications a " +
            "JOIN instance_templates t ON a.template_id = t.template_id " +
            "WHERE a.cloud_type = #{cloudType} " +
            "AND a.status = 'approved' " +
            "AND a.is_deleted = 0") // 新增删除标记条件
    Map<String, Object> getCloudStats(String cloudType);
    //用户取消申请
    @Delete("DELETE FROM applications WHERE apply_id = #{applyId} AND status = 'pending'")
    int cancelApplication(Integer applyId);
    @Delete("DELETE FROM schedule_jobs WHERE apply_id = #{applyId}")
    int deleteScheduleJobsByApplyId(Integer applyId);
    //找到已经处理的操作记录
    @Select("SELECT " +
            "a.apply_id, a.cloud_type, a.status, a.apply_time, a.handle_time, " +
            "a.account_info, a.reject_reason, a.name, a.role, a.school_id, " +
            "a.email, a.phone, t.cpu_cores, t.memory_gb, a.gpu_enabled " + // 确保字段正确
            "FROM applications a " +
            "JOIN instance_templates t ON a.template_id = t.template_id " +
            "WHERE a.status IN ('approved', 'rejected') " +
            "AND a.is_deleted = 0 " +
            "ORDER BY a.apply_time DESC")
    List<Map<String, Object>> findProcessedApplications();

    //管理员删除操作记录
    @Update("UPDATE applications SET is_deleted = 1 WHERE apply_id = #{applyId}")
    int logicalDelete(Integer applyId);

    //写入申请表
    @Insert("INSERT INTO applications (" +
            "user_id, cloud_type, template_id, gpu_enabled, status, " +
            "name, role, school_id, email, phone, duration_days, expire_time) " +
            "VALUES (" +
            "#{userId}, #{cloudType}, #{templateId}, #{gpuEnabled}, #{status}, " +
            "#{name}, #{role}, #{schoolId}, #{email}, #{phone}, #{durationDays}, #{expireTime})")
    @Options(useGeneratedKeys = true, keyProperty = "applyId")
    int insert(Application application);


    // 新增方法：根据applyId查询申请详情（包含openid）
    @Select("SELECT a.*, u.openid FROM applications a " +
            "JOIN users u ON a.user_id = u.user_id " +
            "WHERE a.apply_id = #{applyId}")
    Application findById(Integer applyId);

    // 新增方法：更新申请状态和资源回收信息
    @Update("UPDATE applications SET " +
            "status = #{status}, " +
            "account_info = #{accountInfo} " + // 可选字段更新
            "WHERE apply_id = #{applyId}")
    int update(Application application);

    //新创建的要找到所有细节
    @Select("SELECT " +
            "a.apply_id, a.cloud_type, a.status, a.apply_time, a.handle_time, " +
            "a.account_info, a.reject_reason, a.gpu_enabled, a.name, a.role, " +
            "a.school_id, a.expire_time, " + // 确保包含expire_time
            "t.cpu_cores, t.memory_gb, t.gpu_supported, " +
            "u.openid " +
            "FROM applications a " +
            "JOIN instance_templates t ON a.template_id = t.template_id " +
            "JOIN users u ON a.user_id = u.user_id " +
            "WHERE a.apply_id = #{applyId}")
    ApplicationDetailVO findDetailById(Integer applyId);
}